package com.community.common.core.utils;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.community.common.core.exception.CommunityException;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;

@Slf4j
public class JWTUtils {

    private static Algorithm sign = Algorithm.HMAC256("Java2207-ts-pom");

    /**
     * 生成一个Token，把key和value放入到JWT的载荷
     *
     * @param key
     * @param val
     * @return
     */
    public static String createToken(String key, Object val) {
        return JWT.create().withClaim(key, JSON.toJSONString(val)).sign(sign);
    }

    /**
     * 生成一个Token，把key和value放入到JWT的载荷,具备过期时间
     *
     * @param key
     * @param val
     * @param time 单位是毫秒
     * @return
     */
    public static String createToken(String key, Object val, Long time) {
        Date exp = new Date(System.currentTimeMillis() + time);
        return JWT.create().withClaim(key, JSON.toJSONString(val)).withExpiresAt(exp).sign(sign);
    }

    /**
     * 校验token，token校验成功返回DecodedJWT对象
     * @param token
     * @return
     */
    public static DecodedJWT checkToken(String token) {
        try {
            return JWT.require(sign).build().verify(token);
        } catch (TokenExpiredException e) {
            throw new CommunityException("Token已过期");
        } catch (JWTVerificationException e) {
            throw new CommunityException("Token校验异常");
        }
    }
}
